<template>
  <view class="edit-wrapper">
    <view class="wrapper-scroll">
      <view class="view-block mb-50">
        <uni-forms class="cust-form" ref="form" :modelValue="form" :rules="rules" label-position="top">
          <uni-forms-item name="contractorName">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">项目名称</text>
              </view>
            </template>
            <uni-easyinput v-model="form.contractorName" placeholder="请输入..." disabled></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="responsiblePersonId">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">责任人</text>
              </view>
            </template>
            <uni-data-select v-model="form.responsiblePersonId" :localdata="personList" placeholder="请选择..." :disabled="sbDisabled"></uni-data-select>
          </uni-forms-item>

          <uni-forms-item name="inspectorName">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">检查人</text>
              </view>
            </template>
            <uni-easyinput v-model="form.inspectorName" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="inspectionTime">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">检查时间</text>
              </view>
            </template>
            <uni-datetime-picker type="date" v-model="form.inspectionTime" placeholder="请选择..." :disabled="sbDisabled" />
          </uni-forms-item>
          <uni-forms-item name="riskLevel">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">风险等级</text>
              </view>
            </template>
            <uni-data-select v-model="form.riskLevel" :localdata="riskLevelList" placeholder="请选择..." :disabled="sbDisabled"></uni-data-select>
          </uni-forms-item>

          <uni-forms-item name="inspectionType">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">检查类型</text>
              </view>
            </template>
            <uni-data-select v-model="form.inspectionType" :localdata="inspectionTypeList" placeholder="请选择..." :disabled="sbDisabled"></uni-data-select>
          </uni-forms-item>

          <uni-forms-item name="inspectionMethod">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">检查方式</text>
              </view>
            </template>
            <uni-data-select v-model="form.inspectionMethod" :localdata="inspectionMethodList" placeholder="请选择..." :disabled="sbDisabled"></uni-data-select>
          </uni-forms-item>

          <uni-forms-item name="problemDesc">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">问题描述</text>
              </view>
            </template>
            <uni-easyinput type="textarea" v-model="form.problemDesc" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="rectificationRequirement">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">整改要求</text>
              </view>
            </template>
            <uni-easyinput type="textarea" v-model="form.rectificationRequirement" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="isUnsafeBehavior">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">是否不安全行为</text>
              </view>
            </template>
            <uni-data-checkbox v-model="form.isUnsafeBehavior" :localdata="unsafeBehaviorList" :disabled="sbDisabled" />
          </uni-forms-item>
          <uni-forms-item name="rectificationDays">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">整改天数</text>
              </view>
            </template>
            <uni-easyinput v-model="form.rectificationDays" type="number" @change="daysOnChange" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="rectificationTime">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">整改完成时间</text>
              </view>
            </template>
            <uni-easyinput v-model="form.rectificationTime" placeholder="请输入..." disabled></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item>
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">附件上传</text>
              </view>
            </template>

            <uni-file-picker
              class="cust-file-upload"
              v-model="fileList"
              :custSty="true"
              :auto-upload="false"
              file-mediatype="all"
              file-extname="jpeg,jpg,png"
              :list-styles="uploadListSty"
              @select="fileOnSelect"
              :disabled="sbDisabled"
              :class="{ hideuploadSty: sbDisabled }"
              @custPreview="preview"
            >
              <view class="cust-file-upload-btn">
                <image class="upload-icon" src="/static/images/common/file-upload.png" mode=""></image>
                <text class="upload-title">上传附件</text>
                <text class="upload-subtitle">只能上传jpg/png文件，且不超过5MB</text>
              </view>
            </uni-file-picker>
          </uni-forms-item>
        </uni-forms>
      </view>

      <view class="view-block mb-50" v-if="sbDisabled">
        <uni-forms class="cust-form" ref="form2" :modelValue="form" :rules="rules" label-position="top">
          <uni-forms-item name="rectificationSituation">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">整改情况</text>
              </view>
            </template>
            <uni-easyinput type="textarea" v-model="form.rectificationSituation" placeholder="请输入..." :disabled="zgDisabled"></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item>
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">附件上传</text>
              </view>
            </template>
            <uni-file-picker
              class="cust-file-upload"
              v-model="fileList2"
              :custSty="true"
              :auto-upload="false"
              file-mediatype="all"
              file-extname="jpeg,jpg,png"
              :list-styles="uploadListSty"
              @select="fileOnSelect"
              :disabled="zgDisabled"
              :class="{ hideuploadSty: zgDisabled }"
              @custPreview="preview"
            >
              <view class="cust-file-upload-btn">
                <image class="upload-icon" src="/static/images/common/file-upload.png" mode=""></image>
                <text class="upload-title">上传附件</text>
                <text class="upload-subtitle">只能上传jpg/png文件，且不超过5MB</text>
              </view>
            </uni-file-picker>
          </uni-forms-item>
        </uni-forms>
      </view>
    </view>
    <view class="fixed-btn-box">
      <view v-if="dialogType == 1" class="cust-btn" @click="submitForm(1)">提交填报</view>
      <view v-else-if="dialogType == 2" class="cust-btn" @click="submitForm(2)">审 核</view>
      <view v-else class="cust-btn" @click="goBack()">返 回</view>
    </view>

    <msg-popup ref="msgPopup">
      <template #content>
        <view class="cust-msg-content">
          <view class="title">提示信息</view>
          <view class="msg">{{ popMsg }}</view>
        </view>
      </template>
    </msg-popup>
  </view>
</template>

<script>
import dayjs from 'dayjs';
import { required } from '@/utils/rules';
import { getInspectionRecords, addInspectionRecords, updateInspectionRecords, examIneInspectionRecords } from '@/api/person/inspectionRecords';
import { getActive } from '@/api/person/process';
import { listAllPerson } from '@/api/person/person';
import { uploadFiles } from '@/api/system/common.js';
import config from '@/config';

export default {
  data() {
    return {
      popMsg: '',
      id: null,
      form: {
        contractorName: null,
        isUnsafeBehavior: 0,
        rectificationTime: null
      },
      rules: {
        responsiblePersonId: { rules: [required('责任人不能为空')] },
        inspectorName: { rules: [required('检查人不能为空')] },
        inspectionTime: { rules: [required('检查时间不能为空')] },
        riskLevel: { rules: [required('风险等级不能为空')] },
        inspectionMethod: { rules: [required('检查方式不能为空')] },
        inspectionType: { rules: [required('检查类型不能为空')] },
        problemDesc: { rules: [required('问题描述不能为空')] },
        rectificationRequirement: { rules: [required('整改要求不能为空')] },
        rectificationDays: { rules: [required('整改天数不能为空')] },
        isUnsafeBehavior: { rules: [required('请选择是否不安全行为')] },
        rectificationSituation: { rules: [required('整改情况不能为空')] }
      },
      unsafeBehaviorList: [
        {
          text: '是',
          value: 1
        },
        {
          text: '否',
          value: 0
        }
      ],
      defObj: {},
      personList: [],
      inspectionMethodList: [],
      inspectionTypeList: [],
      riskLevelList: [],
      activeNames: ['1'],
      //上报disable
      sbDisabled: false,
      zgDisabled: false,
      dialogType: 1, // 1: 新增/修改 2: 整改 3: 详情
      fileList: [],
      fileList2: [],
      maxSize: 5 * 1024 * 1024,
      uploadListSty: { dividline: false, border: false },
      baseFileUrl: config.baseFileUrl
    };
  },
  onLoad(option) {
    this.getFrontData();
    if (option && option.id) {
      if (option.type) {
        this.dialogType = option.type;
        this.sbDisabled = option.type == 2 || option.type == 3;
        this.zgDisabled = option.type == 3;
      }
      this.handleData(option.id);
    } else {
      this.getActiveData();
    }
  },
  methods: {
    getFrontData() {
      listAllPerson().then((response) => {
        this.personList = response.data.map((item) => {
          return {
            text: item.employeeName,
            value: item.id
          };
        });
      });
      this.getDicts('risk_level').then((response) => {
        this.riskLevelList = response.data.map((item) => ({
          value: item.dictValue,
          text: item.dictLabel
        }));
      });

      this.getDicts('inspection_type').then((response) => {
        this.inspectionTypeList = response.data.map((item) => ({
          value: item.dictValue,
          text: item.dictLabel
        }));
      });
      this.getDicts('inspection_method').then((response) => {
        this.inspectionMethodList = response.data.map((item) => ({
          value: item.dictValue,
          text: item.dictLabel
        }));
      });
    },
    getActiveData() {
      getActive().then((response) => {
        if (response.code == 200) {
          this.defObj = response.data;
          this.form.contractorId = this.defObj.id;
          this.form.contractorName = this.defObj.companyName;
        }
      });
    },
    handleData(id) {
      getInspectionRecords(id).then((response) => {
        this.form = response.data;
        if (response.data.riskReportingAttachments && response.data.riskReportingAttachments.length) {
          this.fileList = response.data.riskReportingAttachments.map((item) => {
            return { id: item.id, name: item.fileName, url: this.baseFileUrl + item.fileUrl };
          });
        }

        if (response.data.riskRectificationAttachments && response.data.riskRectificationAttachments.length) {
          this.fileList2 = response.data.riskRectificationAttachments.map((item) => {
            return { id: item.id, name: item.fileName, url: this.baseFileUrl + item.fileUrl };
          });
        }
      });
    },
    daysOnChange(val) {
      console.log(val);
      const time = dayjs().add(val, 'day').format('YYYY-MM-DD');
      this.form.rectificationTime = time;
    },
    submitForm(type) {
      this.form.status = type;
      if (type == 1) {
        this.$refs.form.validate().then((res) => {
          if (!this.fileList.length) {
            return this.custPop('请上传附件');
          }
          this.uploadFilesLoop(type);
        });
      }
      if (type == 2) {
        this.$refs.form2.validate().then((res) => {
          if (!this.fileList2.length) {
            return this.custPop('请上传附件');
          }
          this.uploadFilesLoop(type);
        });
      }
    },
    fileOnSelect(e) {
      const files = e.tempFiles || e.tempFilePaths || [];
      console.log(e, files);
      const tempFiles = files.filter((f) => {
        const ok = (f.size || 0) <= this.maxSize;
        if (!ok) {
          uni.showToast({
            title: '文件不能超过5MB',
            icon: 'none'
          });
        }
        return ok;
      });
      if(this.sbDisabled && !this.zgDisabled){
        this.fileList2 = [...this.fileList2, ...tempFiles];
      }else{
        this.fileList = [...this.fileList, ...tempFiles];
      }
      
    },
    async uploadFilesLoop(type) {
      if (type == 1) {
        this.form.riskReportingAttachments = [];
        for (var i = 0; i < this.fileList.length; i++) {
          let item = this.fileList[i];
          if (item.id) {
            this.form.riskReportingAttachments.push({
              id: item.id,
              fileName: item.name,
              fileUrl: item.url
            });
          } else {
            let filePath = item.url || item;
            let params = { name: 'files', filePath: filePath };
            let res = await uploadFiles(params);
            if (res.code == 200) {
              this.form.riskReportingAttachments.push({
                fileName: res.newFileNames,
                fileUrl: res.urls
              });
            }
          }
        }

        console.log(this.form.riskReportingAttachments);

        this.applyFn();
      }

      if (type == 2) {
        this.form.riskRectificationAttachments = [];
        for (var i = 0; i < this.fileList2.length; i++) {
          let item = this.fileList2[i];
          if (item.id) {
            this.form.riskRectificationAttachments.push({
              id: item.id,
              fileName: item.name,
              fileUrl: item.url
            });
          } else {
            let filePath = item.url || item;
            let params = { name: 'files', filePath: filePath };
            let res = await uploadFiles(params);
            if (res.code == 200) {
              this.form.riskRectificationAttachments.push({
                fileName: res.newFileNames,
                fileUrl: res.urls
              });
            }
          }
        }
        let params = {
          id: this.form.id,
          rectificationSituation: this.form.rectificationSituation,
          riskRectificationAttachments: this.form.riskRectificationAttachments
        };
        examIneInspectionRecords(params).then((response) => {
          this.navPop('整改成功');
        });
      }
    },
    applyFn() {
      if (this.form.id != null) {
        updateInspectionRecords(this.form).then((response) => {
          this.navPop('修改成功');
        });
      } else {
        addInspectionRecords(this.form).then((response) => {
          this.navPop('新增成功');
        });
      }
    },
    preview(item) {
      uni.previewImage({
        urls: [item.url]
      });
    },
    goBack() {
      this.$tab.navigateBack();
    },
    navPop(msg) {
      this.popMsg = msg;
      this.$refs.msgPopup.open();
      setTimeout(() => {
        this.$tab.navigateBack();
      }, 900);
    },
    custPop(msg) {
      this.popMsg = msg;
      this.$refs.msgPopup.open();
      setTimeout(() => {
        this.$refs.msgPopup.close();
      }, 800);
    }
  }
};
</script>

<style lang="scss" scoped>
.edit-wrapper {
  height: 100%;

  .wrapper-scroll {
    height: calc(100% - 114rpx);
    overflow-y: auto;
  }

  .view-block {
    background: #fff;
    padding: 30rpx;
  }

  ::v-deep .view-block2 {
    .uni-textarea-textarea {
      color: #102c59;
      font-size: 26rpx;
    }
  }
}
.mb-50 {
  margin-bottom: 50rpx;
}
.cust-msg-content {
  text-align: center;
  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: #000000;
    line-height: 72rpx;
    padding-top: 180rpx;
  }
  .msg {
    font-size: 32rpx;
    font-weight: 500;
    color: #000000;
    line-height: 64rpx;
  }
}

.danger {
  margin-left: 30rpx;
}

::v-deep .uni-section .uni-section-header {
  padding: 20rpx 30rpx;
}
::v-deep .uni-section__content-title {
  font-weight: 500;
}

.cust-file-upload {
  &-btn {
    width: 100%;
    border-radius: 10rpx 10rpx 10rpx 10rpx;
    border: 1px solid #2e7dff;
    padding: 20rpx 32rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    .upload-icon {
      width: 44rpx;
      height: 44rpx;
    }
    .upload-title {
      font-weight: 500;
      font-size: 32rpx;
      color: #2e7dff;
      padding-top: 10rpx;
    }

    .upload-subtitle {
      font-weight: 500;
      font-size: 20rpx;
      color: rgba(46, 125, 255, 0.5);
    }
  }
  /deep/.file-picker__progress {
    display: none;
  }
}
.cust-file-upload.hideuploadSty {
  ::v-deep .files-button,
  ::v-deep.icon-del-box {
    display: none;
  }
  ::v-deep.files__name {
    margin-right: 0;
  }
}

::v-deep .checklist-box.is--default.is-disable .checklist-text {
  color: #102c59 !important;
}
::v-deep .is-disable .checklist-text {
  opacity: 1 !important;
}
</style>
